/**
 * 
 */
package bingo.component.dhtmlxgrid.config;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * XML序列化和反序列化类
 * @author elvis
 */
public final class XMLSerializer {
	
	private static Log logger = LogFactory.getLog(XMLSerializer.class);
	
	public static final String DEFAULT_XML_ENCODING = "UTF-8";

	private static XStream xstream = new XStream(new DomDriver());
	
	static {
		xstream.alias("head", Head.class);
		xstream.alias("column", Column.class);
		xstream.alias("settings", Settings.class);
		xstream.alias("call", Call.class);
		xstream.alias("param", Param.class);		
		xstream.addImplicitCollection(Head.class, "columns");
		xstream.addImplicitCollection(AfterInit.class, "calls");
		xstream.addImplicitCollection(BeforeInit.class, "calls");
		xstream.addImplicitCollection(Call.class, "params");
		xstream.useAttributeFor(Call.class,"command");		 
		xstream.registerConverter(new ColumnConverter());
		xstream.registerConverter(new ParamConverter());
	}
	
	public static Object unserializeFromXMLStream(InputStream in){
        if(null != in){
            InputStreamReader reader = null;
            try{
                reader  = new InputStreamReader(in,Charset.forName(DEFAULT_XML_ENCODING));
                
                return xstream.fromXML(reader);
            }finally{
                if(null != reader){
                    try {
                        reader.close();
                    } catch (IOException e) {
                    	logger.error(e);
                    }
                }
            }
        }else{
            return null;
        }	    
	}
	
    /**
     * 把XML反序列化为对象
     */
    public static Object unserializeFromXMLResource(String xmlResource){
        return unserializeFromXMLStream(XMLSerializer.class.getResourceAsStream(xmlResource));
    }
    

    /**
     * 把XML反序列化为一个对象
     * @param xml 对象的XML内容
     * @return 反序列化后的对象
     */
    public static Object unserializeFromXML(String xml){
        return xstream.fromXML(xml);
    }
    
    /**
     * 把对象序列化为XML 
     */
    public static String serializeToXML(Object object){
    	return xstream.toXML(object);
    }
}
